package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {

    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list",name = "查询所有部门信息")
    public String findAll(String companyId, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Dept> pageInfo = deptService.findByPage(page, pageSize, getCompanyId());
        request.setAttribute("page", pageInfo);
        return "/system/dept/dept-list";
    }

    @RequestMapping(value = "toAdd",name = "跳转到新增部门页面")
    public String add() {
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "/system/dept/dept-add";
    }

    @RequestMapping(value = "/toUpdate",name = "跳转到修改部门页面")
    public String toUpdate(String id) {
        Dept dept = deptService.findById(id);
        request.setAttribute("dept", dept);
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "/system/dept/dept-update";
    }

    @RequestMapping(value = "edit",name = "保存部门信息")
    public String save(Dept dept) {
        // 判断parent_id是否为“”，如果是设置其值为null，因为后台表的parent_id有外键约束，不能为"",但可以为null
        if ("".equals(dept.getParent().getId())){
            dept.setParent(new Dept());
        }
        dept.setCompanyId(getCompanyId());
        dept.setCompanyName(getCompanyName());
        if (StringUtils.isEmpty(dept.getId())) {
            String id = UUID.randomUUID().toString();
            dept.setId(id);
            deptService.save(dept);
        } else {
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "delete",name = "删除部门信息")
    public String deleteById(String id) {
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do";
    }
}
